var websocket=null;
var username=null;
var receiverId=null;
var senderId=null;
$(function(){
	addList();//初始化聊天列表
	websockt();
	
	$("#sendMessage").click(function(){//发送消息
		var content=$("#content").val();
		var receiverName=$("#receiver").text();
		var senderName=$("#username").text();
		if(receiverName!=''){
			console.info(receiverId+";"+receiverName+";"+senderId+";"+senderName);
			sendMessage(content,receiverId,receiverName,senderId,senderName);
		}else{
			layer.msg("请选择聊天对象");
		}
	});
})
//Enter发送
document.onkeydown = function (e) {
    var ev = document.all ? window.event : e;
    if (ev.keyCode == 13) {
    	$("#sendMessage").click();   
    }
}
//websocket方法
function websockt(){
	username=document.getElementById("username").innerText;
	websocket=new WebSocket("ws://localhost:8090/user/websocket/"+username);
	//连接成功的方法
	websocket.onopen=function(){
		console.info(username+"连接成功");
  	}
  	//连接关闭的回调方法
	websocket.onclose = function () {
		console.info("WebSocket连接关闭");
	}
	//接收到消息的回调方法  
	websocket.onmessage = function(event) {  
  		 var data = event.data;
  		 var obj = JSON.parse(data);
  		 if(obj.online=='1'){//上线通知
  			 var username=obj.username;
  			 $("#senderId").val(obj.senderId);
  			 onlineNotice(username);//通知上线
  			 setLine(true,username);//更改状态
  		 }else if(obj.online=='2'){//一对一通知
  			 if((obj.sysChat.sender==senderId && obj.sysChat.receiver==receiverId) || (obj.sysChat.sender==receiverId &&  obj.sysChat.receiver== senderId) ){
  				var message=obj.sysChat.message;
  				var time = new Date();
  				//'+time.toLocaleString( )+'<br>
  				if(obj.sysChat.sender==senderId){
  					$("#message").append('<div class="myMessage">我：'+message+'</div>'); 
  				}else if(obj.sysChat.sender==receiverId){
  					$("#message").append('<div class="">'+obj.sysChat.senderName+'：'+message+'</div>'); 
  				}
  			 }else if(receiverId==null || senderId==null){
  				 var sender=obj.sysChat.senderName;
  				 setMessageCount(true,sender);
  			 }
  		 }else if(obj.online=='3'){//下线通知
  			 var username=obj.username;
  			 //offlineNotice(username);
  			 setLine(false,username);
  		 }else if(obj.online=='4'){//不在线
  			 var usermessage=obj.sysChat.message;
  			 var message=usermessage+"<br/><font>您正在发送离线消息..<br>";
  			 $("#message").append('<div class="myMessage">我：'+message+'</div>'); 
  		 }
  	}
}
//发送消息
function sendMessage(content,receiver,receiverName,sender,senderName){
	 var socketMessage={message:content,receiver:receiver,receiverName:receiverName,sender:sender,senderName:senderName};
	 websocket.send(JSON.stringify(socketMessage));//json
	 $("#content").val("");
}
//上线更改列表上的状态
function setLine(online,username){
		$(".user").each(function(){
		    var user=$(this).text().split(" ",1);
		    if(user==username){
		    	var onlineCount=$("#onlineCount").text();//更改在线人数
		    	if(online){
		    		$(this).find('.usernameSpan').html(username+" <font color='#00CC66'>[在线]</font>");
		  			$("#onlineCount").text(parseInt(onlineCount)+1);
		    	}else{
		    		$(this).find('.usernameSpan').html(username+" <font color='#C8C8C8;'>[离线]</font>");
		  			$("#onlineCount").text(parseInt(onlineCount)-1);
		    	}
		    }
		  });
}
//未查看消息
function setMessageCount(unread,username){
	$(".user").each(function(){
	    var user=$(this).find(".usernameSpan").text().split(" ",1);
	    if(user==username){
	    	if(unread){
	    		var count=$(this).find('span').text();
	    		console.info("-"+count+"-");
	    		if(count==""){
                    count = 1 ;
                }else{
                	count++;
                }
	    		$(this).find('span').text(count);
	    		$(this).find('span').addClass("messageCount");
	    	}else{
	    		
	    	}
	    }
	  });
}
window.onbeforeunload=function(){
	websocket.onclose();
}
  //在线列表
function addList(){
	  $.ajax({
          async: false,
          type: "post",
          url: "/user/chatUser.html",
          success: function(data) {
         		var userList=data.userList;
         		$.each(userList, function (i, item) {  
         			 var onlineStatus=item.onlineStatus;
         			 var username=item.username;
         			 var unRead=item.unRead;
         			 var messageCount="";
         			 if(unRead>0){
         				messageCount='<span class="messageCount">'+unRead+'</span>'
         			 }else{
         				messageCount='<span class=""></span>';
         			 }
         			 if(onlineStatus==1){//在线
         				username=username+" <font color='#00CC66;'>[在线]</font>";
         			 }else{
         				username=username+" <font color='#C8C8C8;'>[离线]</font>"; 
         			 }
         			 $(".listUl").append('<li class="user"><input type="hidden" value='+item.id+'><img src='+item.headPortrait+'>'+messageCount+'<sapn class="usernameSpan">'+username+'</span></li>');
         			 
         		})
          }
      });
  }
//点击用户列表  
$(document).on("click",".user",function(){
	  $("#message").empty();
	  senderId=$("#senderId").text();
	  $(this).addClass('selected').siblings().removeClass('selected');
	  var userId=$(this).children().attr("value");//获取用户ID
	  $("#receiverId").val(userId);
	  receiverId=$("#receiverId").val();
	  var username=$(this).find(".usernameSpan").text().split(" ",1);
	  $("#receiver").text(username);
	  //设置样式&拉取未读消息
	  var messageCount=$(this).find(".messageCount").text();
	  if(messageCount>0){
		  $(this).find('span').removeClass("messageCount");
		  $(this).find('span').text("");
		  //设置通知数
		  var count=$("#count").text();
		  var remainRead=parseInt(count)-messageCount;
		  if(remainRead==0){//全部读完
			  $("#count").text("");
			  $("#read").attr("class","");
		  }
	  }
	  //拉取未读信息
	  $.ajax({
          async: false,
          type: "post",
          url: "/user/readMessage.html",
          data:{sender:receiverId,receiver:senderId},
          success: function(data) {
        	  var list=data.list;
         	  $.each(list, function (i, item) { 
         		  var sender=item.sender;
         		  if(senderId==sender){
         			 $("#message").append('<div class="myMessage">我：'+item.message+'</div>'); 
         		  }else{
         			  $("#message").append('<div class="myMessage">'+username+'：'+item.message+'</div>');  
         		  }
         	  })
          }
      });
 })
//页面关闭
$(window).unload(function(){
//这里面写在关闭页面时，要调用的事件
    alert("页面要关闭了");
});

 
  